package sweetcamera;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.ImageLocalSelectActivity;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.MicAddActivity;
import com.github.postsanf.yinian.activity.UpLoadActivity;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.Bimp;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;

public class CameraPublishActivity extends BaseActivity implements View.OnClickListener {
    private RelativeLayout image_rl;
    private RelativeLayout hongbao_tip;
    private ImageView image_show;
    private ImageView camerapublish_label_tip;
    private LinearLayout cp_label_text, cp_label_mic, cp_label_img, cp_label_hongbao;
    private TextView cp_label_text_tx, cp_label_mic_tx, cp_label_img_tx, cp_label_hongbao_tx;
    public static String content = "";
    private ConnectivityManager mConnectivityManager;
    private String fsize;
    SharedPreferences.Editor editor;
    private UploadManager mUpManager;
    private String imagelocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camerapublish);
        sendBroadcast(new Intent(ACTIONs.actionCloseTimeGoodsAlbum));
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        mUpManager = application.getUploadManager();
        registerBoradcastReceiver();
        if (getIntent() != null && !StringUtils.isEmpty(getIntent().getStringExtra("imagelocal"))) {
            imagelocal = getIntent().getStringExtra("imagelocal");
        }
        initView();
    }


    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("updateContent");
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        myIntentFilter.addAction("updateImageNum");
        myIntentFilter.addAction("updateMoney");
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.titlt_publish).setOnClickListener(this);
        hongbao_tip = (RelativeLayout) findViewById(R.id.hongbao_tip);
        image_show = (ImageView) findViewById(R.id.image_show);
        image_rl = (RelativeLayout) findViewById(R.id.image_rl);
        cp_label_text = (LinearLayout) findViewById(R.id.cp_label_text);
        cp_label_text.setOnClickListener(this);
        cp_label_text_tx = (TextView) findViewById(R.id.cp_label_text_tx);
        cp_label_mic = (LinearLayout) findViewById(R.id.cp_label_mic);
        cp_label_mic.setOnClickListener(this);
        cp_label_mic_tx = (TextView) findViewById(R.id.cp_label_mic_tx);
        cp_label_img = (LinearLayout) findViewById(R.id.cp_label_img);
        cp_label_img.setOnClickListener(this);
        cp_label_img_tx = (TextView) findViewById(R.id.cp_label_img_tx);
        cp_label_hongbao = (LinearLayout) findViewById(R.id.cp_label_hongbao);
        cp_label_hongbao.setOnClickListener(this);
        cp_label_hongbao_tx = (TextView) findViewById(R.id.cp_label_hongbao_tx);
        camerapublish_label_tip = (ImageView) findViewById(R.id.camerapublish_label_tip);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, UIHelper.getCameraPublishImgHigh(this));
        rlp.setMargins(UIHelper.dip2px(this, 14), UIHelper.dip2px(this, 14), UIHelper.dip2px(this, 14), 0);
        image_rl.setLayoutParams(rlp);
//        image_show.setImageBitmap(bitmap);
        if (!StringUtils.isEmpty(imagelocal)) {
            Glide.with(CameraPublishActivity.this).load(Uri.parse("file://" + imagelocal)).into(image_show);
        }
        findViewById(R.id.btns_text).setOnClickListener(this);
        findViewById(R.id.btns_img).setOnClickListener(this);
        findViewById(R.id.btns_mic).setOnClickListener(this);
        findViewById(R.id.btns_hongbao).setOnClickListener(this);
        updateContent();
        updateMIc();
        updateImage();
        updateMoney();
        updateTip();
        boolean hbTipZhidaole = SpUtils.getBoolean(CameraPublishActivity.this, "hbTipZhidaole");
        if (!hbTipZhidaole) {
            hongbao_tip.setVisibility(View.VISIBLE);
        }
        hongbao_tip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hongbao_tip.setVisibility(View.GONE);
                SpUtils.put(CameraPublishActivity.this, "hbTipZhidaole", true);
            }
        });
    }

    private String jieTuUrlkey;

    private void getTokenCamera() {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetPrivateSpaceUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            mUpManager.put(imagelocal, UUID.randomUUID().toString() + ".jpg", resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                            mProgressDialog.dismiss();
                                            jieTuUrlkey = key;
//                                            Log.i("xjs", "jieTuUrlkey==>" + jieTuUrlkey);
                                            if (SelectedImg.mSelectedImage.size() > 0) {
                                                fsize = SizeFormat.formatSize(UIHelper.getupstorge());
                                                if (!ImageLocalSelectActivity.IsSmall) {
                                                    pd = ProgressDialog.show(CameraPublishActivity.this, "", "发布中...", false, false);
                                                    mHandler.sendEmptyMessage(1);
                                                } else {
                                                    pd = ProgressDialog.show(CameraPublishActivity.this, "", "压缩中...", false, false);
                                                    new Thread() {
                                                        @Override
                                                        public void run() {
                                                            super.run();
                                                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                                                if (!SelectedImg.mSelectedImage.get(i).startsWith("http")) {
                                                                    String mubiaostr = Bimp.compressImage2(SelectedImg.mSelectedImage.get(i), mTempDir);
                                                                    SelectedImg.mSelectedImage.set(i, mubiaostr);
                                                                }
                                                            }
                                                            mHandler.sendEmptyMessage(1);
                                                        }
                                                    }.start();
                                                }
                                            } else {
                                                mProgressDialog.dismiss();
                                                UploadToYiNian();
                                            }
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                        }
                                    }, null));
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.titlt_publish:
                if (StringUtils.isEmpty(imagelocal))
                    return;
                getTokenCamera();
                break;
            case R.id.btns_text:
            case R.id.cp_label_text:
                startActivity(new Intent(this, CameraPublishTextActivity.class));
                break;
            case R.id.btns_img:
            case R.id.cp_label_img:
                startActivity(new Intent(this, ImageLocalSelectActivity.class));
                break;
            case R.id.btns_mic:
            case R.id.cp_label_mic:
                startActivity(new Intent(this, MicAddActivity.class));
                break;
            case R.id.btns_hongbao:
                startActivity(new Intent(this, CameraPublishHongbaoActivity.class));
                break;
        }
    }

    public static String totalMoney = "";
    public static String totalNum = "";

    private void UploadToYiNian() {
        String urlsto = "https://api.zhuiyinanian.com/YinianProject/event/UploadScanEvent";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        mParam.put(CommonConstants.YNS_CONTENT, content);
        mParam.put(CommonConstants.YNS_PIC_ADDRESS, "");
//        mParam.put(CommonConstants.YNS_EPLACE, "");
//        mParam.put(CommonConstants.YNS_PIC_MODE, "private");
        mParam.put(CommonConstants.YNS_AUDIO, MainActivity.micUrl);
//        mParam.put(CommonConstants.YNS_PLACE, "");
//        mParam.put(CommonConstants.YNS_PLACEPIC, "");
//        mParam.put(CommonConstants.YNS_PLACELONGITUDE, "");
//        mParam.put(CommonConstants.YNS_PLACELATITUDE, "");
//        mParam.put(CommonConstants.YNS_PEOPLENAME, "");
        mParam.put(CommonConstants.YNS_VERIFYPICADDRESS, jieTuUrlkey);
        mParam.put(CommonConstants.YNS_TOTALNUM, totalNum);
        mParam.put(CommonConstants.YNS_TOTALMONEY, totalMoney);
//        mParam.put(CommonConstants.YNS_MAIN, "1");
        mParam.put(CommonConstants.YNS_SOURCE, SystemUtils.getAppStoreName(CameraPublishActivity.this, "UMENG_CHANNEL"));
        if (CameraActivity.fromfrist) {
            mParam.put(CommonConstants.YNS_IS_PUSH, "no");
            mParam.put(CommonConstants.YNS_GROUP_ID, CameraActivity.fromfristgid + "");
        } else {
            mParam.put(CommonConstants.YNS_IS_PUSH, "yes");
            mParam.put(CommonConstants.YNS_GROUP_ID, application.getCurGid() + "");
        }
        String upstorage = SizeFormat.formatDouble(UIHelper.getupstorge(), SizeFormat.FZ_KB);
        mParam.put(CommonConstants.YNS_STORAGE, upstorage);
        Log.i("xjs", "mParam.toString==>" + mParam.toString());
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resStatus = gson.fromJson(s, YNStatusResponse.class);
                        Log.i("xjs", "uploadsssssss==>" + s.toString());
                        if (ReqUtils.isSuccess(resStatus.getCode())) {
                            if (resStatus.getData() != null) {
                                YNStatus mstatus = resStatus.getData().get(0);
                                YNSingleton.getInstance().setCurStatus(mstatus);
                                // 通知动态更新
                                Intent mIntent = new Intent(ACTIONs.actionStatus);
                                mIntent.putExtra(ACTIONs.IsAdd, true);
                                mIntent.putExtra(ACTIONs.StatusId, mstatus.getEid());
                                sendBroadcast(mIntent);
                                sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                                sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                            }
                            File mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
                            if (mTempDir.exists()) {
                                mTempDir.delete();
                            }
                            sendBroadcast(new Intent(ACTIONs.actionCloseAlbum).putExtra(ACTIONs.aIsClearSelect, 1));
                            finish();
//                            clearAll();
                        } else {
                            showToast(resStatus.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionMIcText:
                    updateMIc();
                    updateTip();
                    break;
                case "updateImageNum":
                    updateImage();
                    updateTip();
                    break;
                case "updateContent":
                    updateContent();
                    updateTip();
                    break;
                case "updateMoney":
                    totalMoney = intent.getStringExtra("totalPrice");
                    totalNum = intent.getStringExtra("totalgeshu");
                    updateMoney();
                    updateTip();
                    break;

            }
        }
    };


    private void updateMIc() {
        if (!StringUtils.isEmpty(MainActivity.micUrl)) {
            if (MainActivity.mp3IsExist) {
                cp_label_mic_tx.setText(TimeUtils.secToTime(MainActivity.timer));
                cp_label_mic.setVisibility(View.VISIBLE);
            } else {
                cp_label_mic_tx.setText("");
                cp_label_mic.setVisibility(View.GONE);
            }
        } else {
            cp_label_mic_tx.setText("");
            cp_label_mic.setVisibility(View.GONE);
        }
    }


    private void updateImage() {
        if (SelectedImg.mSelectedImage.size() > 0) {
            cp_label_img_tx.setText("已添加" + SelectedImg.mSelectedImage.size() + "张照片");
            cp_label_img.setVisibility(View.VISIBLE);
        } else {
            cp_label_img_tx.setText("");
            cp_label_img.setVisibility(View.GONE);
        }
    }

    private void updateContent() {
        if (!StringUtils.isEmpty(content)) {
            cp_label_text_tx.setText(content);
            cp_label_text.setVisibility(View.VISIBLE);
        } else {
            cp_label_text_tx.setText("");
            cp_label_text.setVisibility(View.GONE);
        }
    }

    private void updateMoney() {
        if (!StringUtils.isEmpty(totalMoney) && !StringUtils.isEmpty(totalNum)) {
            cp_label_hongbao.setVisibility(View.VISIBLE);
        } else {
            cp_label_hongbao.setVisibility(View.GONE);
        }
    }

    private void updateTip() {
        if (cp_label_text.getVisibility() == View.VISIBLE || cp_label_mic.getVisibility() == View.VISIBLE || cp_label_img.getVisibility() == View.VISIBLE || cp_label_hongbao.getVisibility() == View.VISIBLE) {
            camerapublish_label_tip.setVisibility(View.GONE);
        } else {
            camerapublish_label_tip.setVisibility(View.VISIBLE);
        }
    }


    private ProgressDialog pd;
    private File mTempDir;

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                if (pd != null)
                    pd.dismiss();
                if (mConnectivityManager.getActiveNetworkInfo() != null && mConnectivityManager.getActiveNetworkInfo().isAvailable()) {
                    if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
                        doUpImg(false);
                    } else if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE) {
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            doUpImg(false);
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                } else {
                    if (pd != null)
                        pd.dismiss();
                }
            }
        }
    };


    private ProgressDialog mProgressDialog;

    private void doUpImg(boolean isPause) {
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishElement);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, application.getCurGid() + "");
        mIntent.putExtra(ACTIONs.aContent, content);
        mIntent.putExtra(ACTIONs.upaudio, MainActivity.micUrl);
        mIntent.putExtra(ACTIONs.upplace, MainActivity.locationTx);
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(UIHelper.getupstorge(), SizeFormat.FZ_KB));
        mIntent.putExtra(CommonConstants.YNS_VERIFYPICADDRESS, jieTuUrlkey);
        mIntent.putExtra(CommonConstants.YNS_TOTALNUM, totalNum);
        mIntent.putExtra(CommonConstants.YNS_TOTALMONEY, totalMoney);
        mIntent.putExtra(CommonConstants.YNS_SOURCE, SystemUtils.getAppStoreName(CameraPublishActivity.this, "UMENG_CHANNEL"));
        mIntent.putExtra(CommonConstants.YNS_IS_PUSH, "yes");
        Log.i("xjs", "CameraActivity.fromfrist==>" + CameraActivity.fromfrist);
        if (CameraActivity.fromfrist) {
            mIntent.putExtra("isPush", "no");
            mIntent.putExtra(ACTIONs.aGid, CameraActivity.fromfristgid + "");
        } else {
            mIntent.putExtra(ACTIONs.aGid, application.getCurGid() + "");
        }
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        sendBroadcast(new Intent(ACTIONs.actionCloseAlbum));
        mProgressDialog.dismiss();
        finish();
    }

    public void FristNetWork(String fsize) {
        final android.support.v7.app.AlertDialog dlg = new android.support.v7.app.AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(true);
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    public void SecondNetWork(String fsize) {
        final android.support.v7.app.AlertDialog dlg = new android.support.v7.app.AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

}
